package com.example.springblog.interceptor;

import com.example.springblog.constant.Constants;
import com.example.springblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Controller
@Component//交给spring管理，别的地方用的时候才能用@Autowired注入
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        //2.校验token，判断是否放行
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);//user_token
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseToken(token);
        if(claims==null){
            //校验失败
            response.setStatus(401);//这里设置的response状态码码，也是前端进行判断后端是否成功的依据
            return false;
        }
        return true;

    }
}
